using Services;
using UnityEngine;

[System.Serializable]
public class SleepController
{
    private EventSystem eventSystem;
    private Enemy target;

    [SerializeField]
    private ESleepMode mode;
    [SerializeField]
    private float t_sleep;
    [SerializeField]
    private float t_awake;
    private float timer_sleep;
    private float timer_awake;

    public void Initialize(Enemy enemy)
    {
        eventSystem = ServiceLocator.Get<EventSystem>();
        target = enemy;
        target.State = mode == ESleepMode.None ? EEnemyState.Patrol : EEnemyState.Sleep;
        switch (mode)
        {
            case ESleepMode.Temporary:
                eventSystem.AddListener<float>(EEvent.Tick, Tick_Sleep);
                break;
            case ESleepMode.Persistent:
                eventSystem.AddListener<float>(EEvent.Tick, Tick_Sleep);
                eventSystem.AddListener<float>(EEvent.Tick, Tick_Awake);
                break;
        }
    }

    private void Tick_Sleep(float t)
    {
        switch (target.State)
        {
            case EEnemyState.Sleep:
                timer_sleep += t;
                if (timer_sleep > t_sleep)
                {
                    timer_awake = 0f;
                    target.State = EEnemyState.Patrol;
                    if (mode == ESleepMode.Temporary)
                        Stop();
                }
                break;
            case EEnemyState.Patrol:
                if (mode != ESleepMode.Periodic)
                    Stop();
                break;
            default:
                Stop();
                break;
        }
    }

    private void Tick_Awake(float t)
    {
        switch (target.State)
        {
            case EEnemyState.Sleep:
                break;
            case EEnemyState.Patrol:
                timer_awake += t;
                if (timer_awake > t_awake)
                {
                    timer_sleep = 0f;
                    target.State = EEnemyState.Sleep;
                }
                break;
            default:
                Stop();
                break;
        }
    }

    private void Stop()
    {
        switch (mode)
        {
            case ESleepMode.Temporary:
                eventSystem.RemoveListener<float>(EEvent.Tick, Tick_Sleep);
                break;
            case ESleepMode.Periodic:
                eventSystem.RemoveListener<float>(EEvent.Tick, Tick_Sleep);
                eventSystem.RemoveListener<float>(EEvent.Tick, Tick_Awake);
                break;
        }
    }
}
